package utils;
import java.util.StringTokenizer;


public class ByteArrayManip {
	public static void addIntToByteArray(int value, byte[] dest, int offset) {
        dest[offset] =(byte)(value >>> 24);
        dest[offset+1] =(byte)(value >>> 16);
        dest[offset+2] =(byte)(value >>> 8);
        dest[offset+3] =(byte) value;
	}
	
	public static int getIntFromByteArray(byte[] b, int offset){
		return (b[offset] << 24)
        + ((b[offset+1] & 0xFF) << 16)
        + ((b[offset+2] & 0xFF) << 8)
        + (b[offset+3] & 0xFF);
	}
	
	public static void addIpToByteArray(String ip, byte[] dest, int offset) {
		StringTokenizer st = new StringTokenizer(ip, ".");
		if(st.countTokens() != 4) {
			throw new IllegalArgumentException();
		}
		for(int i = 0; i < 4; i ++) {
			String s = st.nextToken();
			int value = Integer.parseInt(s);
			dest[offset + i] = (byte) value;
		}
	}
	
	public static String getIpFromByteArray(byte[] b, int offset) {
		StringBuilder sb = new StringBuilder();
		for(int i = 0; i < 4; i ++) {
			int value = (int)b[offset + i] & 0xff;
			sb.append(value);
			sb.append('.');
		}
		sb.deleteCharAt(sb.length()-1);
		return sb.toString();
	}
}
